﻿
using System.Collections.Generic;
using System.Drawing;
using Silvermoon.OpenGL.Native;
using Silvermoon.OpenGL;
using Silvermoon.Utils;

namespace Silvermoon.Visuals
{
    /// <summary>
    /// Visual that creates a texture that holds a string. See also <seealso cref="VisualString"/>.
    /// Note that ImageStringVisual renders significantly faster than StringVisual but also requires more memory.
    /// </summary>
    public class ImageStringVisual : RectangleVisual
    {
        public static readonly Font DefaultFont = new Font(FontFamily.GenericSerif, 9, FontStyle.Regular);
        public static readonly Font DefaultBoldFont = new Font(FontFamily.GenericSansSerif, 9, FontStyle.Bold);

        private string text;
        private Texture texture;
        private FontSprite textureFont;
        private Size textSize;

        public string Text
        {
            get { return text; }
            set
            {
                if (text != value)
                {
                    text = value;
                    textSize = Size.Empty;
                    Invalidate();
                }
            }
        }

        public FontSprite Font
        {
            get
            {
                if (textureFont == null) textureFont = FontSprite.Regular;
                textSize = Size.Empty;
                return textureFont;
            }
            set
            {
                if (textureFont != value)
                {
                    textureFont = value;
                    Invalidate();
                }
            }
        }

        public override Size Size
        {
            get
            {
                return RectangleUtil.MinSize(TextSize);
            }
        }

        public Size TextSize
        {
            get
            {
                if (textSize.IsEmpty)
                {
                    textSize = Font.MeasureString(Text);
                }

                return textSize;
            }
        }

        private void CreateTexture()
        {
            IsInitialized = false;
        }

        protected override void CreateElements()
        {
            Texture imgTexture = new Texture();
            using (Graphics g = imgTexture.CreateGraphics(Size.Width, Size.Height, GlesPixelFormat.RGB, Color.Transparent))
            {
                g.Clear(Color.Black);
                using (SolidBrush brush = new SolidBrush(Color.White))
                {
                    g.DrawString(text, Font.Font, brush, 0F, 0F);
                }
            }
            texture = imgTexture;

            base.CreateElements();
        }


        public override void Invalidate()
        {
            texture = null;
            base.Invalidate();
        }
    }
}
